package com.example.controller;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.config.Result;
import com.example.service.*;
import com.example.pojo.MsslyyBook;
import com.example.pojo.User;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.utils.PageUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.*;

@RestController
@RequestMapping("/api/msslyyBook")
@Api(tags = "图书表")
public class MsslyyBookController {
    @Resource
    private MsslyyBookService msslyyBookService;
    @Resource
    private MsslyyWishlistService msslyyWishlistService;
    @Resource
    private MsslyyFootprintService msslyyFootprintService;
    @Resource
    private MsslyyCartService msslyyCartService;
    @Resource
    private MsslyyCategoryService msslyyCategoryService;
    @Resource
    private MsslyyPublisherService msslyyPublisherService;
    @Resource
    private HttpServletRequest request;
    @Resource
    private UserService userService;
    @Resource
    private PageUtils pageUtils;

    public User getUser() {
        String token = request.getHeader("token");
        String username = JWT.decode(token).getAudience().get(0);
        return userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUsername, username));
    }

    @ApiOperation(value = "新增图书",notes = "")
    @PostMapping
    public Result<?> save(@RequestBody MsslyyBook msslyyBook) {
        msslyyBookService.save(msslyyBook);
        return Result.success();
    }

    @ApiOperation(value = "下单之后扣除图书数量",notes = "")
    @PostMapping("/decrQuantity/{bookId}/{quantity}")
    public Result<?> decrQuantity(@PathVariable Long bookId,@PathVariable Integer quantity) {
        MsslyyBook book = msslyyBookService.getById(bookId);
        book.setBookQuantityOutput(book.getBookQuantityOutput()+quantity);
        boolean b = msslyyBookService.updateById(book);
        return Result.success(b);
    }

    @ApiOperation(value = "更新图书",notes = "")
    @PutMapping
    public Result<?> update(@RequestBody MsslyyBook msslyyBook) {
        msslyyBookService.updateById(msslyyBook);
        return Result.success();
    }

    @ApiOperation(value = "删除图书",notes = "")
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        msslyyBookService.removeById(id);
        return Result.success();
    }

    @ApiOperation(value = "根据id查询",notes = "")
    @GetMapping("/{id}")
    public Result<?> findById(@PathVariable Long id) {
        return Result.success(msslyyBookService.getById(id));
    }

    @ApiOperation(value = "查询全部",notes = "")
    @GetMapping
    public Result<?> findAll() {
        QueryWrapper<MsslyyBook> queryWrapper=new QueryWrapper<>();
        LambdaQueryWrapper<MsslyyBook> msslyyBookLambdaQueryWrapper = queryWrapper.lambda().orderByDesc(MsslyyBook::getId);
        List<MsslyyBook> list = msslyyBookService.list(msslyyBookLambdaQueryWrapper);
        return Result.success(list);
    }

    /**
     * 畅销书籍
     * @return
     */
    @ApiOperation(value = "畅销书籍",notes = "")
    @GetMapping("/selling")
    public Result<?> findSelling() {
        QueryWrapper<MsslyyBook> queryWrapper=new QueryWrapper<>();
        LambdaQueryWrapper<MsslyyBook> msslyyBookLambdaQueryWrapper = queryWrapper.lambda().orderByDesc(MsslyyBook::getBookQuantityOutput);
        List<MsslyyBook> list = msslyyBookService.list(msslyyBookLambdaQueryWrapper);
        return Result.success(list);
    }

    /**
     * 特价商品
     * @return
     */
    @ApiOperation(value = "特价商品",notes = "")
    @GetMapping("/specialOffer")
    public Result<?> specialOffer() {
        QueryWrapper<MsslyyBook> queryWrapper=new QueryWrapper<>();
        LambdaQueryWrapper<MsslyyBook> msslyyBookLambdaQueryWrapper = queryWrapper.lambda().orderByAsc(MsslyyBook::getBookNewPrice);
        List<MsslyyBook> list = msslyyBookService.list(msslyyBookLambdaQueryWrapper);
        return Result.success(list);
    }

    /**
     * 随机推荐
     * @return
     */
    @ApiOperation(value = "随机推荐",notes = "")
    @GetMapping("/randomRecommend")
    public Result<?> randomRecommend() {
        List<MsslyyBook> list = msslyyBookService.list();
        int size = list.size();
        HashSet<MsslyyBook> books = new HashSet<>();
        if (size>=8){
            while (books.size()<8){
                int i = new Random().nextInt(size);
                if (list.get(i)!=null) books.add(list.get(i));
            }
        }
        return Result.success(books);
    }


    /**
     * 您也许会喜欢
     * @return
     */
    @ApiOperation(value = "也许你会喜欢",notes = "")
    @GetMapping("/like")
    public Result<?> like() {
        List<MsslyyBook> list = msslyyBookService.list();
        int size = list.size();
        HashSet<MsslyyBook> books = new HashSet<>();
        if (size>=4){
            while (books.size()<4){
                int i = new Random().nextInt(size);
                if (list.get(i)!=null) books.add(list.get(i));
            }
        }
        return Result.success(books);
    }

    /**
     * 其他同类产品4种
     * @return
     */
    @ApiOperation(value = "其他同类产品4种",notes = "")
    @GetMapping("/classIf/{classIf}/{bookId}")
    public Result<?> classIf(@PathVariable Integer classIf,@PathVariable Integer bookId) {
        QueryWrapper<MsslyyBook> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("category_id",classIf);
        queryWrapper.ne("book_id",bookId);
        List<MsslyyBook> list = msslyyBookService.list(queryWrapper);
        if (list.size()>=4) {
            return Result.success(list.subList(0,4));
        }else {
            return Result.success(list);
        }



    }

    @ApiOperation(value = "分页",notes = "")
    @GetMapping("/page")
    public Result<?> findPage(@RequestParam(required = false, defaultValue = "") String name,
                              @RequestParam(required = false, defaultValue = "") Long categoryId,
                              @RequestParam(required = false, defaultValue = "") Long publisherId,
                              @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<MsslyyBook> query = Wrappers.<MsslyyBook>lambdaQuery().orderByDesc(MsslyyBook::getId);
        if (StrUtil.isNotBlank(name)) {
            query.like(MsslyyBook::getBookTitle, name);
        }
        if (categoryId!=0) {
            query.eq(MsslyyBook::getCategoryId, categoryId);
        }
        if (publisherId!=0) {
            query.eq(MsslyyBook::getPublisherId, publisherId);
        }
        IPage<MsslyyBook> page = msslyyBookService.page(new Page<>(pageNum, pageSize), query);

        page.getRecords().forEach(e->{
            msslyyPublisherService.list().forEach(p->{
                if (e.getPublisherId()==p.getId()){
                    e.setPublisherName(p.getPublisherName());
                }
            });
            msslyyCategoryService.list().forEach(c->{
                if (e.getCategoryId()==c.getId()){
                    e.setCategoryName(c.getCategoryName());
                }
            });
        });
        return Result.success(page);
    }


    @GetMapping("/getBookListById/{id}")
    public Result<?> getBookListById(
            @PathVariable Long id,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        List books = msslyyWishlistService.getBookListById(id);
        Page pages = pageUtils.getPages(pageNum, pageSize, books);
        return Result.success(pages);
    }

    @GetMapping("/getBookListById2/{id}")
    public Result<?> getBookListById2(
            @PathVariable Long id) {
        List books = msslyyWishlistService.getBookListById(id);
        return Result.success(books);
    }

    @GetMapping("/getFootprintById/{id}")
    public Result<?> getFootprintById(
            @PathVariable Long id,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        List books = msslyyFootprintService.getFootprintById(id);
        Page pages = pageUtils.getPages(pageNum, pageSize, books);
        return Result.success(pages);
    }


    @GetMapping("/getCartById/{id}")
    public Result<?> getCartById(
            @PathVariable Long id,
            @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @RequestParam(required = false, defaultValue = "10") Integer pageSize) {
        List books = msslyyCartService.getCartById(id);
        Page pages = pageUtils.getPages(pageNum, pageSize, books);
        return Result.success(pages);
    }

}
